import os
import sys
import re

basePath = "./assets/resources" # 游戏资源存放路径
outFile = "./assets/script/plugin/ResourcesPath.js" # 该映射关系表的输出路径
outFileDTS = "./ResourcesPath.d.ts" # 资源路径文档
exPaths = []  # 要排除的文件
fileCategorys = [".png", ".PNG", ".jpg", ".mp3",
                 ".wav", ".prefab", ".anim", ".labelatlas"] # 映射资源文件类型

lines = []
resNames = []

if sys.argv[1]:
    basePath = sys.argv[1]
if sys.argv[2]:
    outFile = sys.argv[2]
if sys.argv[3]:
    for i in range(3, len(sys.argv)):
        exPaths.append(sys.argv[i])


def makeResDict():
    print("Read Name And Path Start!")

    for (path, dirs, files) in os.walk(basePath):
        for filename in files:
            if filename.find(".meta") != -1:
                continue

            resName = ""
            for oneCategory in fileCategorys:
                if filename.find(oneCategory) != -1:
                    nameArr = filename.split(".")
                    resName = nameArr[0]
                    break

            if resName == "":
                continue

            #startIndex = path.index(".") + 7

            resPath = path.replace("\\", "/")
            startStr = "assets/resources/"
            startIndex = resPath.index(startStr)+len(startStr)
            resPath = resPath[startIndex:]

            resPath = resPath + "/" + resName

            line = "\t" + resName + " : \"" + resPath + "\",\n"
            if line in lines:
                print("Read Name And Path Error!, res name repeat!  >>>" + resName)
                return False

            if isExPath(resPath) == False:
                lines.append(line)
                resNames.append("\t" + resName + ",\n")

    print("Read Name And Path Success!")
    return True


def isExPath(p):
    for ex in exPaths:
        if re.match(ex, p) != None:
            return True
    return False


def writeFile():
    print("Write Name And Path Start!")

    if not os.path.exists(os.path.dirname(outFile)):
        os.makedirs(os.path.dirname(outFile))

    dst = open(outFile, 'w', encoding='utf-8')
    dst.write("let ResourcesPath = {\n")
    for line in lines:
        dst.write(line)
        print(line)
    dst.write("}")
    dst.write("\n")
    dst.write("window.ResourcesPath = window.ResourcesPath || ResourcesPath;")
    print("Write Name And Path Success!")
    dst.close()

    if not os.path.exists(os.path.dirname(outFileDTS)):
        os.makedirs(os.path.dirname(outFileDTS))

    dst = open(outFileDTS, 'w', encoding='utf-8')
    dst.write("let ResourcesPath = {\n")
    for resName in resNames:
        dst.write(resName)
        print(resName)
    dst.write("}")
    dst.write("\n")
    print("Write ResourcesPath.d.ts Success!")
    dst.close()


def main():
    isOk = makeResDict()
    if isOk:
        lines.sort()
        writeFile()

    os.system('exit')


if __name__ == '__main__':
    main()
